package com.demo.api.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: cja
 * @date: 2019/11/14 15:50
 */
@Component
public class RedisCacheRepository {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存数据
     *
     * @param key
     * @param value
     * @param second 秒（大于等于0生效）
     */
    public void set(String key, String value, Integer second) {
        if (second != null && second > 0) {
            redisTemplate.opsForValue().set(key, value, second, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, value);
        }
    }

    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除数据
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.opsForValue().getOperations().delete(key);
    }
}
